package com.situ.project1.controller;

import com.situ.project1.pojo.Account;
import com.situ.project1.pojo.ChangePasswordRequest;
import com.situ.project1.pojo.Customer;
import com.situ.project1.pojo.User;
import com.situ.project1.service.UserService;
import com.situ.project1.util.JwtUtils;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/users", produces = "application/json;charset=utf-8")
public class UserApi {
    private static final PasswordEncryptor encryptor = new StrongPasswordEncryptor();
    private UserService userService;
    @Value("${jwt.secret.key}")
    private String jwtSecretKey;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Account account, HttpSession session) {
        if (!StringUtils.hasText(account.getCaptcha())) {
            return Map.of("success", false, "error", "验证码不可为空");
        }

        String answer = (String) session.getAttribute("captcha");
        if (!answer.equalsIgnoreCase(account.getCaptcha())) {
            return Map.of("success", false, "error", "验证码不正确");
        }

        if (!StringUtils.hasText(account.getUsername())) {
            return Map.of("success", false, "error", "用户名不可为空");
        }

        if (!StringUtils.hasText(account.getPassword())) {
            return Map.of("success", false, "error", "密码不可为空");
        }

        //1。登录验证
        User user = this.userService.findByUsername(account.getUsername());

        if (user == null) {
            return Map.of("success", false, "error", "无此用户");
        }

        //密码校验
        if (!encryptor.checkPassword(account.getPassword(), user.getPassword())) {
            return Map.of("success", false, "error", "密码不正确");
        }
        Customer customer = userService.getCustomer(user.getUsername());

        //2。颁发令牌
        Map<String, Object> data = Map.of("username", account.getUsername());
        String jwt = JwtUtils.encode(account.getUsername(), data, jwtSecretKey);

        return Map.of("success", true, "jwt", jwt);
    }
    @PostMapping("/change-password")
    public Map<String, Object> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
        String username = changePasswordRequest.getUsername();
        String oldPassword = changePasswordRequest.getOldPassword();
        String newPassword = changePasswordRequest.getNewPassword();

        if (!StringUtils.hasText(username) || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            return Map.of("success", false, "error", "所有字段都必须填写");
        }

        User user = this.userService.findByUser(username);

        if (user == null) {
            return Map.of("success", false, "error", "用户不存在");
        }

        // 确保密码验证逻辑正确
        boolean isPasswordValid = encryptor.checkPassword(oldPassword, user.getPassword());
        if (!isPasswordValid) {
            return Map.of("success", false, "error", "旧密码不正确");
        }

        // 更新密码
        String encryptedNewPassword = encryptor.encryptPassword(newPassword);
        user.setPassword(encryptedNewPassword);

        // 确保用户信息更新逻辑正确
       Boolean isUpdated = this.userService.updateUser(user);
        System.out.println("修改 = " + isUpdated);
        if (!isUpdated){
            return Map.of("success", false, "error", "密码修改失败");
        }else {
            return Map.of("success", true, "message", "密码修改成功");
        }

    }
    @GetMapping("/captcha")
    public void captcha(HttpServletResponse resp, HttpSession session) throws IOException {
        //生成验证码
        SpecCaptcha cap = new SpecCaptcha(170, 35, 4);

        //设置响应头
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0L);

        //将答案存储到session中
        session.setAttribute("captcha", cap.text().toLowerCase());
        cap.out(resp.getOutputStream());
    }
//    根据输入账号查信息
    @GetMapping("/user-emp")
    public Map<String, Object> getUser(@RequestParam String username) {
        System.out.println("username = " + username);
        User user = userService.getUser(username);
        return Map.of("success", true, "user", user);
    }

}
